# 业务类型
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render
from django.core.cache import cache
from apps.business.models import Business_type_model
from apps.config.serializers import Menu_serializer
from apps.business.serializers import Type_serializer
from django.db import transaction

def type_view(request):
    # 查询操作权限
    menu_list = cache.get('menu_list')
    menu_obj = Menu_serializer(menu_list, many=True)
    return render(request, 'type/list.html',{'data':menu_obj.data})
# 序列化成树
def Rec_Dept(datas):
    lists = []
    tree = {}
    parent_id = ''
    for i in datas:
        item = i
        tree[item['id']] = item
    root = None
    for i in datas:
        obj = i
        if not obj['type_business']:
            root = tree[obj['id']]
            lists.append(root)
        else:
            parent_id = obj['type_business']
            if 'children' not in tree[parent_id]:
                tree[parent_id]['children'] = []
            tree[parent_id]['children'].append(tree[obj['id']])
    return lists
# 序列化成正常json
def type_list(request,id):
    if id == 0:
        type_list = Business_type_model.objects.all()
        counts = Business_type_model.objects.count()
    else:
        type_list = Business_type_model.objects.filter(type_business=id)
        counts = Business_type_model.objects.filter(type_business=id).count()
    list = []
    for i in type_list:
        tree_type = Business_type_model.objects.filter(id=i.type_business_id).values_list('type_name', flat=True)
        if len(tree_type) == 0:
            parent_dept = None
        else:
            parent_dept = tree_type[0]
        dict = {}
        dict['id'] = i.id
        dict['type_code'] = i.type_code
        dict['type_name'] = i.type_name
        dict['type_business_id'] = i.type_business_id
        dict['type_pname'] = parent_dept
        dict['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
        dict['now_status'] = i.now_status
        dict['remark_describe'] = i.remark_describe
        list.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    Result = {'code': 0, 'mes': '成功！', 'count': counts, 'data': res}
    return JsonResponse(Result)
# 序列化成树
def type_list1(request):
    try:
        dept_list = Business_type_model.objects.filter()
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': 'Dept_model出现问题！'})
    ser_obj = Type_serializer(dept_list, many=True)
    dept_lists = Rec_Dept(ser_obj.data)
    return JsonResponse({'code': 0, 'data': dept_lists})
# 添加页面
def type_insert_view(request):
    return render(request, 'type/insert.html')

# 添加动作
@transaction.atomic
def type_insert(request):
    # 判断是否具有权限
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '50010101' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    code = request.POST.get('type_code')
    name = request.POST.get('type_name')
    type_pid = request.POST.get('select')
    status = request.POST.get('now_status')
    remark = request.POST.get('remark_describe')
    try:
        Business_type_model.objects.create(type_code=code, type_name=name, type_business_id=type_pid,
                                  now_status=status, remark_describe=remark,
                                  )
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        if e.args[0] == 1406:
            return JsonResponse({'code': 201, 'msg': '数据过长！'})
        if e.args[0] == 1062:
            return JsonResponse({'code': 202, 'msg': '唯一值出现重复！请检查业务类型代码。'})
        else:
            return JsonResponse({'code': 203, 'msg': '未知错误！'})
    return JsonResponse({'code': 0, 'msg': '添加成功！'})

# 修改页面
def type_edit_view(request):
    return render(request, 'type/edit.html')

# 修改动作
@transaction.atomic
def type_edit(request,id):
    # 判断是否有权限id
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '50010102' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    code = request.POST.get('type_code')
    name = request.POST.get('type_name')
    perfix = request.POST.get('type_perfix')
    type_pid = request.POST.get('select')
    status = request.POST.get('now_status')
    remark = request.POST.get('remark_describe')
    try:
        Business_type_model.objects.filter(pk=id).update(type_code=code, type_name=name, type_business_id=type_pid, now_status=status,
                                                remark_describe=remark)
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        if e.args[0] == 1406:
            return JsonResponse({'code': 201, 'msg': '数据过长！'})
        if e.args[0] == 1062:
            return JsonResponse({'code': 202, 'msg': '唯一值出现重复！请检查业务类型代码。'})
        else:
            return JsonResponse({'code': 203, 'msg': '未知错误！'})

    return JsonResponse({'code': 0, 'msg': '修改成功！'})

# 禁用操作
@transaction.atomic
def type_del(request,id):
    # 先得判断是否具有添加权限（50010303）
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    # 判断其是否拥有权限
    if '50010103' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    try:
        type_obj = Business_type_model.objects.get(pk=id)
        if type_obj.now_status==0:
            type_obj.now_status=1
            type_obj.save()
            msg = '禁用成功！'
        else:
            type_obj.now_status = 0
            type_obj.save()
            msg = '启用成功！'
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code': 201, 'msg': '业务类型模块出现问题，请联系管理员！'})
    return JsonResponse({'code': 0, 'msg': msg})
